<template>
    <el-card class="page-container">
      <template #header>
        <div class="header">
          <span>用户信息管理</span>
          <div class="extra">
            <el-button type="primary" @click="openAddUser">添加用户</el-button>
          </div>
        </div>
      </template>
      <!-- 搜索表单 -->
      <el-form inline>
        <el-form-item label="用户名或姓名：">
          <el-input placeholder="请输入用户名或姓名" v-model="searchQuery"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="filterUsers">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 用户信息列表 -->
      <el-table :data="paginatedUsers" style="width: 100%">
        <el-table-column prop="name" label="姓名" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="username" label="用户名" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="gender" label="性别" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column prop="permission" label="权限" width="180"></el-table-column>
        <el-table-column prop="info" label="个人信息" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button @click="editUser(scope.row)" type="primary" size="small">修改</el-button>
            <el-button @click="deleteUser(scope.row)" type="danger" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页条 -->
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 10, 15]"
        layout="jumper, total, sizes, prev, pager, next"
        background
        :total="total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
        style="margin-top: 20px; justify-content: flex-end"
      />
      <!-- 抽屉 -->
      <el-drawer v-model="visibleDrawer" :title="isEdit ? '修改用户' : '添加用户'" direction="rtl" size="50%">
        <!-- 添加用户表单 -->
        <el-form :model="userModel" label-width="100px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="userModel.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userModel.username" :disabled="isEdit" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="userModel.password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="userModel.gender" placeholder="请选择性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="个人信息" prop="info">
            <el-input type="textarea" v-model="userModel.info" placeholder="请输入个人信息"></el-input>
          </el-form-item>
          <el-form-item label="权限" prop="permission">
            <el-select v-model="userModel.permission" placeholder="请选择权限">
              <el-option label="user" value="user"></el-option>
              <el-option label="admin" value="admin"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addUser">{{ isEdit ? '修改' : '添加' }}</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>
    </el-card>
  </template>
  
  <script setup>
  import { ref, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import { userListService, userAddService, userUpdateService, userDeleteService } from '@/api/userApi/user.js';
  
  // 用户列表数据模型
  const users = ref([]);
  const filteredUsers = ref([]);
  const searchQuery = ref('');
  
  // 分页条数据模型
  const pageNum = ref(1); // 当前页
  const total = ref(0); // 总条数
  const pageSize = ref(3); // 每页条数
  
  // 控制抽屉是否显示
  const visibleDrawer = ref(false);
  const isEdit = ref(false); // 控制是否为编辑状态
  
  // 添加表单数据模型
  const userModel = ref({
    id: null,
    name: '',
    username: '',
    password: '',
    gender: '',
    info: '',
    permission: ''
  });
  
  // 打开添加用户表单
  const openAddUser = () => {
    isEdit.value = false;
    userModel.value = {
      id: null,
      name: '',
      username: '',
      password: '',
      gender: '',
      info: '',
      permission: ''
    };
    visibleDrawer.value = true;
  };
  
  // 获取用户列表数据
  const userList = async () => {
    let result = await userListService();
  
    // 渲染视图
    users.value = result.data.map(item => ({
        id: item.id,
        name: item.name,
        username: item.username,
        gender: item.gender,
        info: item.info,
        permission: item.permission
    }));
    filteredUsers.value = users.value;
    total.value = filteredUsers.value.length;
  };
  
  // 计算当前页显示的数据
  const paginatedUsers = computed(() => {
    const start = (pageNum.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return filteredUsers.value.slice(start, end);
  });
  
  // 当每页条数发生了变化，调用此函数
  const onSizeChange = (size) => {
    pageSize.value = size;
    userList();
  };
  
  // 当前页码发生变化，调用此函数
  const onCurrentChange = (num) => {
    pageNum.value = num;
    userList();
  };
  
  // 过滤用户列表
  const filterUsers = () => {
    const query = searchQuery.value.toLowerCase();
    filteredUsers.value = users.value.filter(user => 
      user.name.toLowerCase().includes(query) || 
      user.username.toLowerCase().includes(query)
    );
    total.value = filteredUsers.value.length;
  };
  
  // 重置搜索
  const resetSearch = () => {
    searchQuery.value = '';
    filterUsers();
  };
  
  // 添加用户
  const addUser = async () => {
    let userData = { ...userModel.value };
    if (!userData.password) {
      delete userData.password; // 如果密码为空，则删除密码字段
    }
    let result;
    if (isEdit.value) {
      result = await userUpdateService(userData);
      ElMessage.success(result.msg ? result.msg : '修改成功');
    } else {
      result = await userAddService(userData);
      ElMessage.success(result.msg ? result.msg : '添加成功');
    }
    visibleDrawer.value = false;
    userList();
  };
  
  // 编辑用户
  const editUser = (user) => {
    isEdit.value = true;
    userModel.value = { ...user, password: '' }; // 编辑时将密码字段设为空
    visibleDrawer.value = true;
  };
  
  // 删除用户
  const deleteUser = async (user) => {
    await userDeleteService(user.id);
    ElMessage.success('删除成功');
    userList();
  };
  
  // 初始化用户列表
  userList();
  </script>
  
  <style lang="scss" scoped>
  .page-container {
    min-height: 100%;
    box-sizing: border-box;
  
    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
  </style>